package com.gulimall.authserver.controller;

/*import com.gulimall.authserver.feign.ThirdPartFeignService;
import com.gulimall.authserver.vo.UserRegistVo;
import com.gulimall.common.constant.AuthServerConstant;
import com.gulimall.common.exception.BizCondeEnume;
import com.gulimall.common.utils.R;

import com.netflix.client.ClientException;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;*/

import com.alibaba.fastjson.TypeReference;
import com.gulimall.authserver.feign.MemberFeignServise;
import com.gulimall.authserver.feign.ThirdPartFeignService;
import com.gulimall.common.exception.BizCondeEnume;
import com.gulimall.common.vo.MemberRespVo;
import com.gulimall.common.vo.UserLoginVo;
import com.gulimall.common.vo.UserRegistVo;
import com.netflix.client.ClientException;
import com.gulimall.common.constant.AuthServerConstant;
import com.gulimall.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Controller
@RequestMapping("/login/")
public class LoginController {
    @Autowired
    ThirdPartFeignService thirdPartFeignService;
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    MemberFeignServise memberFeignServise;
/**
 * 发送一个请求直接跳转页面。
 * springmvc viewcontroller;将请求和页面直接映射过来
 */

    /**
     * 登录
     */
 /*   @RequestMapping("login")
    public String login(){
        return  "login.html";
    }
    *//**
     * 注册
     * @return
     *//*
    @RequestMapping("reg")
    public String reg(){
        return "reg.html";
    }*/

    /**
     * 获取短信验证码
     *
     * @param phone
     * @return
     * @throws ClientException
     */
    @PostMapping("sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam("phone") String phone) throws ClientException {
        System.out.println(phone);
        //发验证码之前先判断redis是否有或者有没有到时间
        String redisCode = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone);
        System.out.println(StringUtils.isEmpty(redisCode));
        if (!StringUtils.isEmpty(redisCode)) {
            //转成long时间
            long l = Long.parseLong(redisCode.split("_")[1]);
            //如果当前时间减去redis中存储的时间小于60
            if (System.currentTimeMillis() - l < 60000) {
                //60秒内不能再发
                return R.error(BizCondeEnume.SMS_CODE_EXCEPTION.getCode(), BizCondeEnume.SMS_CODE_EXCEPTION.getMsg());
            }
        }
        //1.接口防刷
        //2.验证码的再次校验 ：rides  存key-phone  sme:code:phone
        String code = UUID.randomUUID().toString().substring(0, 5);
        //String code="123456";
        String substring = code + "_" + System.currentTimeMillis();
        //rides缓存验证码 ，防止同一个手机号在60秒内再次发送验证码 十分钟有效

        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, substring, 10, TimeUnit.MINUTES);
        String phone1 = thirdPartFeignService.Phone(phone, code);
        return R.ok();
    }

    /**
     * 注册成功重定向 到登录页面
     */
    /**
     * //TODO重定向携带数据，利用session原理，将数据放在session中，
     * 只要跳到下一个页面取出这个数据以后，session中的数据就会删掉
     * //TODO 分布式情况下session问题.
     * RedirectAttributes redirectAttributes:模拟重定向携带数据
     *
     * @param vo
     * @param result
     * @param model
     * @param attributes
     * @return
     */
    @PostMapping("/regist")
    public String regit(@Valid UserRegistVo vo, BindingResult result, Model model, RedirectAttributes attributes) {
        //vo.setPhone("123456");
        System.out.println(vo.toString());
        if (result.hasErrors()) {
           /* result.getFieldErrors().stream().map(fieldError -> {
                String field=fieldError.getField();
                String defaultMessage=fieldError.getDefaultMessage();
                errors.put(field,defaultMessage);
                return
            });*/
            /*Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(fieldError -> {
                return fieldError.getField();
            }, fieldError -> {
                return fieldError.getDefaultMessage();
            }));*/
            //前置校验
         /*   Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField
            ,FieldError::getDefaultMessage));
            model.addAttribute("errors",errors);
            redirectAttributes.addFlashAttribute("errors",errors);*/

            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField,
                    FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors", errors);


            Map<String, ?> flashAttributes = attributes.getFlashAttributes();
            System.out.println(flashAttributes.get("errors"));

            //Request method 'POST' not supported
            //用户注册-》/regist[post]--->转发/reg (路径映射默认都是get方式访问的。)
            //如果校验出错，转发到注册页面
            return "redirect:/reg";
        }
        //1.校验验证码
        String code = vo.getCode();
        String s = redisTemplate.opsForValue().get(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
        if (!StringUtils.isEmpty(s)) {
            if (code.equals(s.split("_")[0])) {
                //删除验证码  令牌机制
                redisTemplate.delete(AuthServerConstant.SMS_CODE_CACHE_PREFIX + vo.getPhone());
                //验证码通过
                //真正注册，调用远程服务进行注册
                System.out.println("ok");
                R r = memberFeignServise.regist(vo);
                if (r.getCode() == 0) {
//成功
                    return "redirect:/login/login";
                } else {
                    //失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:/reg";
                }
            } else {
                //验证不通过
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors", errors);
                //如果校验出错，转发到注册页面
                return "redirect:/reg";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            attributes.addFlashAttribute("errors", errors);
            //如果校验出错，转发到注册页面
            return "redirect:/reg";
        }
        //注册成功回到登录页面
//        return "redirect:/login";
    }

    /*
     * 登录提交
     * @param vo
     * @return
     */
    @PostMapping("/login1")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session) {
        System.out.println(vo.toString());
        //修改成商品页面
        //远程登录
        R login = memberFeignServise.login(vo);
        if (login.getCode() == 0) {
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            System.out.println("logn:" + login.toString());
            //成功放到session
            session.setAttribute(AuthServerConstant.LOGIN_USER, data);
            System.out.println("sdfdsf:" + session.getAttribute("loginUser").toString());
            System.out.println(session.getAttribute("loginUser")!=null?1:0);
            return "redirect:http://192.168.188.1:88/api/product";
        } else {
            Map<String, String> errors = new HashMap<>();
            // errors.put("msg",login.getData("msg",new TypeReference<String>(){}));
            errors.put("msg", "账号密码错误");

            redirectAttributes.addFlashAttribute("errors", errors);

            System.out.println(errors.toString());
            return "redirect:http://localhost:88/login/login";
        }
    }

    @GetMapping("/login")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute != null) {
            return "redirect:http://192.168.188.1:88/api/product";
        } else {
            return "login.html";
        }

    }
}
